package com.muyan.sys.webscoket.listener;

import com.alibaba.fastjson2.JSON;
import com.muyan.sys.webscoket.util.ChannelManager;
import com.muyan.sys.webscoket.protocol.MessageProto;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ChatMessageListener {
    @Autowired
    private  ChannelManager channelManager;

    
    /**
     * 监听聊天消息队列
     */
    //@RabbitListener(queues = "chat.queue")
    @RabbitListener(queues = "#{chatQueue.name}", containerFactory = "mqConsumerListenerFactory")
    public void handleChatMessage(String message) {
        try {
            MessageProto chatMessage = JSON.parseObject(message, MessageProto.class);
            String toUserId = chatMessage.getToUserId();
            
            // 检查用户是否在当前服务器
            Channel toChannel = channelManager.getChannel(toUserId);
            if (toChannel != null && toChannel.isActive()) {
                toChannel.writeAndFlush(new TextWebSocketFrame(message));

            }
            log.info("转发消息到用户: {}", toUserId);
        } catch (Exception e) {
            log.error("处理聊天消息异常", e);
        }
    }
} 